<?php
/**
 * Class for working with files
 *
 */
class Db_File extends Db_Table
{
    /**
     * Object type. Match folder name with files
     *
     * @var string
     */
    var $_type = 'product'; //object type
    
    /**
     * Constructor
     *
     * @param string $type object type
     * @return Db_Image
     */
    function Db_File($type='product')
    {
        parent::Db_Table('files');
        $this->_type = $type;
    }
    
    /**
     * Performs insert to file table. Adds last position
     *
     * @param array $data data to insert
     * @return bool operation result
     */
    function insert($data)
    {
        $sql = 'SELECT MAX(pos) FROM ' . $this->table
             . ' WHERE object_type = "' . $this->_type . '"'
             . ' AND object_id = ' . intVal($data['object_id']);

        $data['pos']         = $this->db->getField($sql) + 1;
        $data['object_type'] = $this->_type;
        return parent::insert($data);
    }
    
    /**
     * Delete file from database.
     * Update file positions
     * Remove file files
     *   
     * @param int $id file Id
     */
    function delete($id)
    {
        //find info 
        $file = $this->find($id);
        if (!$file)
            return false;
        $file = $this->makeFileInfo($file);
        //delete db row
        $result = parent::delete($id);
        if (!$result)
            return false;
        
        //update positions
        $sql = 'UPDATE ' . $this->table . ' SET pos = pos-1 '
             . ' WHERE object_type="' . $this->_type . '" '
             . ' AND object_id="' . $file['object_id'] . '" AND pos > ' . $file['pos'];    
        $this->db->query($sql);       
        
        //remove files
        clearstatcache();
        foreach ($file as $k => $v)
            if (false !== strpos($k, 'path') && file_exists($v))
                unlink($v);
        return true;                    
    }    
    
    /**
     * Complete image info
     * with usefull data
     *
     * @param array $info image info
     * @return array updated image info
     */
    function makeFileInfo($info)
    {
        $cfg = _cfg('file.' . $this->_type);
        // use this hack for empty row
        if (!$info)
        {
            $info = $this->getNew();
            $info['id']      = '0';
            $info['mime']    = 'tmp';
        }
        
        // for original image
        $info['url'] = $cfg['url'] . $this->_type . '/' . $info['id'] .  '.' . $info['mime'];
        $info['path'] = $cfg['path'] . $this->_type . '/' . $info['id'] . '.' . $info['mime'];

        return $info;
    }   
         
    /**
     * Find object files
     *
     * @param int $id Object id
     * @return array Array of files info
     */
    function getFiles($id)
    {
        $sql = 'SELECT * FROM ' . _t('files')
            . ' WHERE object_type = "'.$this->_type.'"'
            . ' AND object_id = ' . $id 
            . ' ORDER BY pos';
         
        $rows = $this->db->getRows($sql);
        for ($i=0; $i < count($rows); $i++)
            $rows[$i] = $this->makeFileInfo($rows[$i]);
    
        return $rows;    
    }       
        
       
    /**
    * Update object files position
    *
    * @param array $position Array of files position
    * @return bool operation result
    */
    function updatePos($position)
    {
        //check 
        $values = array_values($position);
        if (count($values) != count(array_unique($values)))
        {
            return false;   
        }
        
        //update if check was successful
        foreach ($position as $id => $pos)
        {
            $sql = 'UPDATE '.$this->table
                 . ' SET pos = ' . $pos
                 . ' WHERE id = ' . $id;
            $this->db->query($sql);     
        }

        return true;
    }  
    
   /**
    * Get first object file
    *
    * @param int $id Object Id
    * @return array File info
    */
    function getFirstFile($id)
    {
        $sql = 'SELECT * FROM ' . $this->table
             . ' WHERE object_type = "'.$this->_type.'"'
             . ' AND object_id = ' . intVal($id)
             . ' AND pos = 1';
        $row = $this->db->getRow($sql);
    
        $row = $this->makeFileInfo($row);
                    
        return $row; 
    }
}
?>